<template>
  <CommonPage>
    <MyTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="roleApi.getRoles"
      :index="true"
      list-key="/role:get"
    >
      <template #action>
        <n-button v-permission="`/role:post`" type="primary" @click="handleAdd">添加角色</n-button>
      </template>
    </MyTable>
    <MyModal
      ref="$form"
      :model-form="model"
      :disabled="type === 'view'"
      :width="900"
      @submit="handleSubmit"
    >
      <n-form-item
        label="角色名称"
        path="name"
        :rule="{ required: true, message: '请输入角色名称' }"
      >
        <n-input v-model:value="model.name" maxlength="10" show-count clearable />
      </n-form-item>
      <n-form-item label="菜单权限" path="rolePermission">
        <n-tree
          :checked-keys="model.rolePermission"
          key-field="id"
          checkable
          block-line
          :selectable="false"
          :data="data.menuTree"
          @update:checked-keys="methods.updateCheckedKeys"
        />
      </n-form-item>
    </MyModal>
  </CommonPage>
</template>

<script setup lang="jsx">
import * as roleApi from '@/api/role'
import * as menuApi from '@/api/menu'
import { useCrudPro } from '@/hooks/useCrudPro'
defineOptions({ name: 'RoleIndex' })
const data = reactive({
  menuTree: [],
})
const methods = reactive({
  async getMenuTree() {
    data.menuTree = (await menuApi.getMenuTree()).data
  },
  updateCheckedKeys(keys, _, { action, node }) {
    // console.log(keys, action, node)
    const ids = getIds([node])
    if (action === 'check') {
      keys = [...new Set(keys.concat(ids))]
    } else if (action === 'uncheck') {
      keys = keys.filter((id) => !ids.includes(id))
    }
    model.value.rolePermission = keys
  },
})
function getIds(array, ids = []) {
  array.forEach((item) => {
    if (item.id) {
      ids.push(item.id)
    }
    if (item.children) {
      ids = getIds(item.children, ids)
    }
  })
  return ids
}
const queryItems = ref({})
const columns = [
  {
    title: '角色名称',
    key: 'name',
  },
  {
    title: '创建时间',
    key: 'createTime',
    render: ({ createTime }) => $format(createTime),
  },
  {
    title: '修改时间',
    key: 'updateTime',
    render: ({ updateTime }) => $format(updateTime),
  },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="/role:put" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="/role:delete"
            text
            onClick={() =>
              handleDelete(row.roleId, {
                title: '删除角色',
                content: `请确定是否删除角色：${row.name}`,
              })
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
const { type, model, $form, $table, handleAdd, handleEdit, handleSubmit, handleDelete } =
  useCrudPro({
    name: '角色',
    initForm: {
      roleId: null,
      name: null,
      rolePermission: [],
    },
    apis: {
      add: roleApi.addRole,
      edit: roleApi.editRole,
      del: roleApi.deleteRole,
      info: ({ roleId }) => roleApi.getRole(roleId).then((res) => res.data),
    },
    onShow() {
      methods.getMenuTree()
    },
  })
onBeforeMount(() => {
  methods.getMenuTree()
})
</script>
